//
//  QDMessageListViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/1.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit
import HandyJSON

/// 信息列表的每行row
struct QDMessageListRow: HandyJSON {
    /// 内容
    var content = ""
    /// 显示时间
    var time = ""
    /// 所属内容
    var title = ""
    /// 消息的id
    var titleId = ""
    
    /// 获得高度
    var height: CGFloat {
        get {
            let size = CGSize(width: UIScreen.main.ritl_width - CGFloat(65), height: 1000)
            
            let height = (content as NSString).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [.font: Font.light.font(size: 14)], context: nil).height + 3
            
            return 19 + 22 + 8 + 8 + 17 + 19 + height /*(19 + 8) * 2 + 22 + 17 + height*/
        }
    }
}

private struct QDMessageListRowContainer: HandyJSON {
    
    /// 内容
    var list = [QDMessageListRow]()
}

/// 消息列表
final class QDMessageListViewController: NWTableViewController,QDLargeTitleTableHeaderScrollable {
    
    /// 消息的类型, 01 公告信息 02 行程信息  03 系统通知
    var type: String?
    /// 消息类型名称
    var typeName: String?
    /// 是否存在未读
    var hasUnread: Bool = false
    /// 全部阅读完毕的回调
    var readComplete: (()->())?
    
    /// 所有的数据源
    var list = [QDMessageListRow]()
    
    /// 设置大标题
    var largeTitle: String = "" {
        willSet {
            largeTableHeaderView.title = newValue
        }
    }
    
    
    /// 滚动的模拟大标题
    let largeTableHeaderView = QDLargeTitleTableHeaderView()
    
    
    /// 传递type的初始化方法
    convenience init(type: String, typeName: String,hasUnread: Bool = false){
        self.init()
        self.type = type
        self.typeName = typeName
        self.hasUnread = hasUnread
    }
    
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDMessageDetailTableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    
    override func headerRefreshBeginHandler() {
        currentPage = 0
        requestMessageList()
    }
    
    
    override func footerRefreshBeginHandler() {
        requestMessageList()
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        largeTableHeaderView.frame = CGRect(origin: .zero, size: CGSize(width: ritl_width, height: QDLargeTitleTableHeaderViewNormalHeight))
        largeTableHeaderView.title = typeName ?? ""
        tableView.tableHeaderView = largeTableHeaderView
        
        //开始请求
        requestMessageList()
        if hasUnread { //存在未读，请求消息已读
            requestMessageListAllRead()
        }
    }
    
    
    // MARK: NavigationBar
    override var nav_mutableBarShadowHidden: Bool { return true }
    
    
    // MARK: ScrollViewDelegate
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        tableViewDidScroll(contentOfset: scrollView.contentOffset) { (isShow) in
            setNavigationBarShadowViewHidden(!isShow)
        }
    }
    

    // MARK: UITableViewDataSource
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let rowCell = cell as? QDMessageDetailTableViewCell {
            let msg = list[indexPath.row]
            
            rowCell.titleLabel.text = msg.title
            rowCell.subtitleLabel.text = msg.content
            rowCell.timeLabel.text = msg.time
        }
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return list[indexPath.row].height
    }
}


extension QDMessageListViewController {
    
    /// 请求详细的消息列表
    private func requestMessageList(){
        
        guard let type = self.type else {
            view.showTextHUD(text: "参数不能为空")
            return
        }
        
        QDNetworkingManager.request(url: msgReadDetailListUrl,isArray: true, paramteres: ["type": type,"size":10, "page": currentPage], arraySuccess: { (msg, data) in

            guard let messageList = [QDMessageListRow].deserialize(from: data) as? [QDMessageListRow]  else {
                self.view.showTextHUD(text: "数据结构错误!"); return
            }
            
            self.endHeaderRefreshing()
            self.endFooterRefreshing()
            
            if self.currentPage == 0 {
                self.list = messageList
            }else {
                self.list += messageList
            }
            
            if messageList.count == 0 {
                self.refreshFooter.endRefreshingWithNoMoreData()
            }
            
            self.tableView.reloadData()
            self.currentPage += 1
            
            if messageList.count < 10 {
                self.refreshFooter.endRefreshingWithNoMoreData()
            }
            
            //进行判断
            if self.list.count == 0 {
                self.showNothingView(true)
            }else {
                self.showNothingView(false)
            }
            
        }) { (msg, errorType) in

            self.endHeaderRefreshing()
            self.endFooterRefreshing()
            self.view.showTextHUD(text: msg)
        }
    }


    /// 本类型的接口全部已读
    private func requestMessageListAllRead(){
        
        guard let type = self.type else {
            view.showTextHUD(text: "参数不能为空")
            return
        }
        
        /// 本类型数据接口已经全部读完
        QDNetworkingManager.request(url: msgReadDetailAllUrl, paramteres: ["type":type], success: { (msg, data) in
            
            /// 执行阅读完毕
            self.readComplete?()
            
        }) { (msg, errorType) in
            
        }
    }
}


private extension String {
    
    // 01 公告信息 02 行程信息  03 系统通知
    
    /// 没有消息的图片
    var messageListNothingImage: UIImage? {
        switch self {
        case "02": return "nothing_message".namedImage
        default: return nil
        }
    }
    
    /// 没有消息的文字描述
    var messageListNothingTitle: String? {
        switch self {
        case "02": return "暂无通知"
        default: return nil
        }
    }
}
